#include<iostream>
#include<string>
#include<pthread.h>
#include<unistd.h>
#include<cstdio>
#include<ctime>
#include<stdlib.h>
#include<mutex>

//线程互斥

//抢票逻辑  1000张票 5个线程同时枪
//int tickets=1000;


//抢票出现负数的代码
// void* ThreadRountine(void *args)
// {
//    int id=*(int *)args;
//    delete (int *)args;
//     srand((long)time(nullptr));
//     while (1){
//     if ( tickets> 0 ) {
//     usleep(1000);
//     std::cout<<"i am  [ "<<id<<" ]抢的票是"<<tickets--<<std::endl;
//     tickets--;
//     } 
//     else {
//         break;
//       }
//     }   

// }



class Ticket{
    private:
    int tickets;

    //pthread_mutex_t mtx; //原生线程库,系统级别
     //std::mutex mymtx; //C++ 语言级别
    //int lock; lock++ 申请锁  lock--取消锁
    
    public:
    Ticket():tickets(1000)
    {
        //pthread_mutex_init(&mtx, nullptr);
    }
    bool GetTicket()
    {
        static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

        bool res = true;
       // pthread_mutex_lock(&mtx); 
    
        mymtx.lock();
        //执行这部分代码的执行流就是互斥的，串行执行的！
        if(tickets > 0){
            usleep(1000); //1s == 1000ms 1ms = 1000us
            std::cout << "我是[" << pthread_self() << "] 我要抢的票是: " << tickets << std::endl;
            tickets--; 
            printf("");
            //抢票
        }
        else{
            printf("票已经被抢空了\n");
            res = false;
        }
        //pthread_mutex_unlock(&mtx);
         mymtx.unlock();
        return res;
    }
    ~Ticket()
    {
        //pthread_mutex_destroy(&mtx);
    }
};


void *ThreadRoutine(void *args)
{
    Ticket *t = (Ticket*)args;
    while(true)
    {
        if(!t->GetTicket())
        {
            break;
        }
    }
}

int main()
{
    Ticket *t = new Ticket();

    pthread_t tid[5];
    for(int i = 0; i < 5; i++){
        int *id = new int(i);
        pthread_create(tid+i, nullptr, ThreadRoutine, (void*)t);
    }

    for(int i = 0 ; i < 5; i++){
        pthread_join(tid[i], nullptr);
    }
    return 0;
}